$().ready(function() {
    validateRule();
    layui.use(['form','table'], function() {
        var form = layui.form, table = layui.table;

        form.on('select(townId)', function (data) {
            console.log('townId',data.value);
            getVillages(data.value,form)
        });
    });
});

function update() {
	var url = ctx + "module/citizen/" + ($('#signupForm').find("#id").val() == '' ? "save" : "update");
    $.ajax({
        cache : true,
        type : "POST",
        url : url,
        data : $('#signupForm').serialize(),// 你的formid
        async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            if (data.code == 0) {
                parent.layer.msg("操作成功");
                parent.reLoad();
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);

            } else {
                parent.layer.alert(data.msg)
            }
        }
    });

}

function getVillages(townId,form) {
    $.ajax({
        url : ctx + "module/citizen/villages",
        type : "post",
        data:{
            townId:townId
        },
        success : function(r) {
            console.log('r',r)
            if (r.code==0) {
                console.log("villages",r.villages);

                var villages = r.villages;
                if (villages.length > 0) {
                    $('#villageId').empty();
                    $('#villageId').append(new Option('请选择村居', ''));
                    for (var i = 0; i < villages.length; i++) {
                        $('#villageId').append(new Option(villages[i].townName, villages[i].id));
                    }
                } else {
                    $('#villageId').empty();
                    $('#villageId').append(new Option('暂无村居', ''));
                }
                form.render("select");
            }
        }
    });
}


function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules : {
            townName : {  required : true  },
            villageName : {  required : true  },
            holderName : {  required : true  },
            holderPhone : {  required : true  },
        },
        messages : {
            townName : {
                required : icon + "请输入乡镇名称"
            },
            villageName : {
                required : icon + "请输入村居名称"
            },
            holderName : {
                required : icon + "请输入房主姓名"
            },
            holderPhone : {
                required : icon + "请输入房主电话"
            },
        }
    })
}
